/**
 * 
 */
package br.com.pim.action;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import br.com.pim.connection.ConnectionFactory;
import br.com.pim.dao.FornecedorDAO;
import br.com.pim.form.FornecedorForm;
import br.com.pim.model.FornecedorModel;
import br.com.pim.util.ConstantesGerais;

/**
 * @author douglas.peixoto
 * 
 */
public class FornecedorAction extends DispatchAction {

	
	public ActionForward iniciar(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {

		
		Connection myConn = null;
		FornecedorDAO fDAO = null;
		
			try{
				myConn = new ConnectionFactory().getConnectionMySQL();
				fDAO = new FornecedorDAO(myConn);
				
				req.setAttribute("LISTA_FORNECEDORES", fDAO.buscarTodos());
			}finally{
				if(myConn != null){
					myConn.close();
				}
			
			}
	
		return mapping.getInputForward();
	}

	
	public ActionForward inserir(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
			Connection myConn = null;
			FornecedorModel fModel = null;
			FornecedorDAO fDAO = null;
			FornecedorForm fForm = (FornecedorForm) form;
			
				try{
					myConn = new ConnectionFactory().getConnectionMySQL();
					fModel = fForm.getFornecedor();
					fDAO = new FornecedorDAO(myConn);
					
			if (!(fModel.getCdFornecedor() == 0 || fModel.getNmFornecedor().equals("")|| fModel.getNmFornecedor().length() <= 2|| fModel.getCnpj() >= 14 || fModel.getCnpj() == 0)) {
				fDAO.inserir(fModel);
			
			}

			else {
						ActionErrors  errors = new ActionErrors();
						errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(ConstantesGerais.ERROR_GENERICO));
						super.saveErrors(req, errors);
					}
					
					
				}finally{
					if(!(myConn == null)){
						myConn.close();
					}
						
				}
				
				this.iniciar(mapping, fForm, req, resp);
			return mapping.getInputForward();
	}
	
}
